#
# 命名规则上，采用 项目名+云模块名+时间戳 的形式。保证命名唯一的同时，也便于通过控制台一眼能认出开通的哪个云产品是属于哪个项目的，不至于一个账号上运行多个不同的项目而混乱
# 项目地址： https://gitee.com/HuaweiCloudDeveloper/obs-datax-plugins/blob/master/appstore/main.tf
#
terraform {
        required_providers {
                huaweicloud = {
                        source  = "huawei.com/provider/huaweicloud"
                        version = "1.38.2"
                }
        }
}

# 生成随机16位的随机字符-用于密码
resource "random_string" "password" {
	length           = 16
	special          = true
	override_special = "@"
}

# 定义一些变量，时间戳的作用是避免命名重复。 使用时调用如： ${local.timestamp}
locals {
	timestamp         = formatdate("YYYYMMDDhhmmss", timestamp())
	# ecs 服务器的密码
	ecspassword       = "${random_string.password.result}@wm"
	# 镜像id， 在北京四，镜像来源是发布到了应用商店的镜像。这里是创建服务器时直接拦截网络包拿到的镜像id
	imagesId          = "989a0e86-967a-4c16-b614-a98cb50dc8b3"
	# rds 数据库的密码
	rdspassword       = "${random_string.password.result}@wm1"
	# obs的名称
	obsname           = "datax-${local.timestamp}"
}

# VPC虚拟私有云。对应控制台 https://console.huaweicloud.com/vpc/
resource "huaweicloud_vpc" "vpc" {
  name = "datax_vpc_${local.timestamp}"
  cidr = "192.168.0.0/16"
}
# 子网
resource "huaweicloud_vpc_subnet" "subnet" {
  name       = "datax_subnet_${local.timestamp}"
  cidr       = "192.168.0.0/16"
  gateway_ip = "192.168.0.1"
  vpc_id     = huaweicloud_vpc.vpc.id
}
# 创建安全组
resource "huaweicloud_networking_secgroup" "secgroup"{
	name = "datax_secgroup_${local.timestamp}"
}
# 安全组规则-开放9527端口（为ECS服务，用于网页端访问控制台操作）
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_9527"{
	direction         = "ingress"
	ethertype         = "IPv4"
	protocol          = "tcp"
	ports	          = 9527
	remote_ip_prefix  = "0.0.0.0/0"
	security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-开放22端口（为ECS服务，用于ssh远程连接）
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_22"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "tcp"
        ports             = 22
        remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-开放3306端口（为RDS Mysql服务，服务器可以内网连接Mysql。不用担心暴漏端口问题，mysql只允许内网，不允许外网访问。）
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_3306"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "tcp"
        ports             = 3306
        remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-允许ping程序测试弹性云服务器的连通性
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_ping"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "icmp"
		remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}

# 创建obs桶
resource "huaweicloud_obs_bucket" "obs" {
	bucket = "${local.obsname}"
	acl    = "private"
	tags   = {
		type = "bucket"
		env  = "${local.obsname}"
	}
}

# 获取服务器、RDS数据库的可用区
data "huaweicloud_availability_zones" "myaz" {}
# 创建RDS数据库
resource "huaweicloud_rds_instance" "rds" {
	name              = "datax_rds_${local.timestamp}"
	# 固定一个规格，1核2G的
	flavor            = "rds.mysql.n1.medium.2"
	vpc_id            = huaweicloud_vpc.vpc.id
	subnet_id         = huaweicloud_vpc_subnet.subnet.id
	security_group_id = huaweicloud_networking_secgroup.secgroup.id
	availability_zone = [
		data.huaweicloud_availability_zones.myaz.names[0]
	]

	# 使用按需计费
	charging_mode = "postPaid"

	db {
		type     = "MySQL"
		version  = "5.7"
		password = "${local.rdspassword}"
	}

	volume {
		type = "CLOUDSSD"
		size = 40
	}
}

# 创建弹性公网EIP
# 按流量计费方式，10MB带宽
resource "huaweicloud_vpc_eip" "eip" {
  name = "datax_eip_${local.timestamp}"
  publicip {
    type = "5_bgp"
  }
  bandwidth {
    share_type  = "PER"
    name        = "datax_bandwidth_${local.timestamp}"
    size        = 10
    charge_mode = "traffic"
  }
}

# 搜索服务器规格,2核4G内存的
data "huaweicloud_compute_flavors" "myflavor" {
  availability_zone = data.huaweicloud_availability_zones.myaz.names[0]
  performance_type  = "normal"
  cpu_core_count    = 2
  memory_size       = 4
}
# 创建服务器
# 注意有坑：设置了user_data字段后，admin_pass字段将无效
resource "huaweicloud_compute_instance" "instance" {
  name              = "datax_${local.timestamp}"
 #admin_pass        = "wngMarket#23"
  image_id          = local.imagesId
  flavor_id         = data.huaweicloud_compute_flavors.myflavor.ids[0]
  availability_zone = data.huaweicloud_availability_zones.myaz.names[0]
  security_group_ids= [huaweicloud_networking_secgroup.secgroup.id]

  network {
    uuid = huaweicloud_vpc_subnet.subnet.id
  }
  # 不起作用，没看出啥问题
  # user_data           = "#!/bin/bash\ntouch 1.txt\nbash /home/datax-web-master/build/datax-web-2.1.2/bin/start-all.sh ${huaweicloud_rds_instance.rds.private_ips[0]} 3306 root ${local.rdspassword}\ntouch 2.txt\necho 'root:${local.ecspassword}' | chpasswd\ntouch 3.txt"
  # user_data         = "#!/bin/sh\ncd ~\necho ${local.ecspassword} | passwd root --stdin > /dev/null 2>&1\ntouch /root/install.sh\necho '/home/datax-web-master/build/datax-web-2.1.2/bin/start-all.sh ${huaweicloud_rds_instance.rds.private_ips[0]} 3306 root ${local.rdspassword}'>>/root/install.sh\nchmod -R 777 /root/install.sh\nchmod -x /root/install.sh\nbash /root/install.sh > install.log 2>&1"
  user_data        = "mkdir \test\ntouch install.sh\necho ${local.ecspassword} | passwd root --stdin > /dev/null 2>&1\n"
}

# 将服务器跟弹性公网绑定
resource "huaweicloud_compute_eip_associate" "associated" {
  public_ip   = huaweicloud_vpc_eip.eip.address
  instance_id = huaweicloud_compute_instance.instance.id
}

# 输出ecs服务器的信息
output "服务器信息"{
	value = "服务器IP:${huaweicloud_vpc_eip.eip.address} 远程登录账号:root 远程登录密码:${local.ecspassword}"
}
output "RDS-Mysql数据库信息"{
	value = "rds mysql 内网IP:${huaweicloud_rds_instance.rds.private_ips[0]} 用户名:root 密码:${local.rdspassword}"
}
output "使用指南"{
	value = "访问 http://${huaweicloud_vpc_eip.eip.address}:9527/index.html  登录账号：admin  登录密码：123456  如果打不开说明正在安装中，请等待几分钟再试"
}
